<template>
  <div class="container_box">
    <Breadcrumb :items="['权限管理', '用户列表']" />
    <a-card title="用户列表">
      <div class="flex">
        <a-tree
          @select="handleselect"
          :default-selected-keys="[0]"
          :default-expanded-keys="[0]"
          class="tree_style"
          :data="treeData"
          :row-key="key"
          blockNode
          show-line
          :fieldNames="{ key: 'id', title: 'name', children: 'children' }"
        />

        <div style="flex: 1">
          <a-row style="margin: 16px 0">
            <a-col :span="12">
              <a-input
                :style="{ width: '320px' }"
                v-model="formModel.search"
                @change="fetchData"
                placeholder="请输入姓名"
                allow-clear
              />
            </a-col>
            <a-col class="flex_end" :span="12">
              <a-button type="primary" @click="handleCreate"> 新建 </a-button>
              <a-tooltip content="刷新">
                <div class="action_icon" @click="search"
                  ><icon-refresh size="18"
                /></div>
              </a-tooltip>
            </a-col>
          </a-row>
          <a-table
            row-key="id"
            :loading="loading"
            :pagination="false"
            :columns="columns"
            :data="renderData"
            :bordered="false"
            :size="large"
            @page-change="onPageChange"
          >
            <template #index="{ rowIndex }">
              {{ rowIndex + 1 + (formModel.page - 1) * formModel.limit }}
            </template>
            <template #first_name="{ record }">
              <a-avatar :style="{ backgroundColor: '#3370ff' }" :size="26">
                {{ record.first_name }}
              </a-avatar>
              {{ record.first_name + record.last_name }}
            </template>
            <template #gender="{ record }">
              {{ record.gender === 0 ? '女' : '男' }}
            </template>
            <template #is_active="{ record }">
              <a-tag :color="record.is_active ? 'green' : 'red'">{{
                record.is_active ? '开启' : '禁用'
              }}</a-tag>
            </template>
            <template #role="{ record }">
              <span v-if="!record?.role?.length">-</span>
              <a-tag
                style="margin-left: 3px"
                color="arcoblue"
                v-else
                v-for="item in record.role"
                :key="item.id"
              >
                {{ record.role?.length > 1 ? item.name + ' ; ' : item.name }}
              </a-tag>
            </template>
            <template #dept="{ record }">
              <span v-if="!(record.dept.length)">-</span>
              <a-tag
                style="margin-left: 3px"
                color="arcoblue"
                v-else
                v-for="item in record?.dept"
                :key="item.id"
              >
                {{ record?.dept?.length > 1 ? item.name + ' ; ' : item.name }}
              </a-tag>
            </template>
            <template #post="{ record }">
              <span v-if="!record?.post?.length">-</span>
              <a-tag
                color="arcoblue"
                v-else
                v-for="item in record.post"
                :key="item.id"
              >
                {{ record.post?.length > 1 ? item.name + ' ; ' : item.name }}
              </a-tag>
            </template>
            <template #operations="{ record }">
              <a-button
                v-permission="['admin']"
                type="text"
                @click="handleCreate(record)"
                >编辑</a-button
              >
              <a-dropdown trigger="hover">
                <icon-more style="cursor: pointer;" />
                <template #content>
                  <a-doption>
                    <span @click="updatePwd(record)">修改密码</span>
                  </a-doption>
                      <a-doption>
                    <span @click="handleDel(record)">删除</span>
                  </a-doption>
                </template>
              </a-dropdown>
            </template>
          </a-table>
          <Pagination
            style="margin-bottom: 20px"
            :total="total"
            :page="formModel.page"
            :limit="formModel.limit"
            @pagination="handlePagination"
          />
        </div>
      </div>
    </a-card>
    <createAndEditModal ref="createRef" @submitFrom="submitFrom" />
    <DeleteModal ref="delRef" @submitDel="submitDel" />
    <updatePassward ref="refPassward"/>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, reactive, watch, nextTick, onMounted } from 'vue';
import useLoading from '@/hooks/loading';
import { Message } from '@arco-design/web-vue';
import {
  getUserList,
  createUser,
  updateUser,
  deleteUser,
  getDeptTree,
} from '@/api/list';
import createAndEditModal from './components/createAndEditModal.vue';
import updatePassward from './components/updatePassward.vue';
import type { TableColumnData } from '@arco-design/web-vue/es/table/interface';
const treeData = ref([{ id: 0, name: '全部', children: [] }]);
const generateFormModel = () => {
  return {
    search: '',
    page: 1,
    dept:'',
    limit: 10,
  };
};
const { loading, setLoading } = useLoading(false);
const isCreate = ref(false);
const total = ref<any>(0);
const renderData = ref<any>([]);
const formModel = ref(generateFormModel());
const columns = reactive<TableColumnData[]>([
  {
    title: '序号',
    width: 60,
    dataIndex: 'index',
    slotName: 'index',
  },
  {
    title: '账号',
    dataIndex: 'username',
    ellipsis: true,
    tooltip: true,
    width: 100,
  },
  {
    title: '姓名',
    dataIndex: 'first_name',
    ellipsis: true,
    tooltip: true,
    width: 140,
    slotName: 'first_name',
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 60,
    slotName: 'gender',
  },
  {
    title: '状态',
    dataIndex: 'is_active',
    slotName: 'is_active',
    width: 60,
  },
  {
    title: '电话号码',
    dataIndex: 'mobile',
    ellipsis: true,
    tooltip: true,
    width: 140,
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 180,
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '角色',
    dataIndex: 'role',
    slotName: 'role',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '岗位',
    dataIndex: 'post',
    slotName: 'post',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '部门',
    dataIndex: 'dept',
    slotName: 'dept',
    ellipsis: true,
    tooltip: true,
  },
  {
    title: '加入时间',
    dataIndex: 'date_joined',
    width: 170,
  },
  {
    title: '操作',
    width: 100,
    fixed: 'right',
    dataIndex: 'operations',
    slotName: 'operations',
  },
]);
onMounted(() => {
  getTrees();
});
// 获取tree
const getTrees = async () => {
  try {
    const { data } = await getDeptTree();
    treeData.value[0].children = data;
    fetchData();
  } catch (err) {}
};
// 获取list
const fetchData = async () => {
  setLoading(true);
  try {
    const { data } = await getUserList(formModel.value);
    renderData.value = data.item;
    total.value = data.total;
  } catch (err) {
    // you can report use errorHandler or other
  } finally {
    setLoading(false);
  }
};
// 设置密码
const refPassward = ref<any>(null)
const updatePwd = (val:any) => {
    refPassward.value.handleClick(val)
}
// 点击树形
const handleselect = (val: any) => {
    formModel.value.dept = (val && val[0]) || '';
  fetchData();
};
// 分页
const handlePagination = (val: any) => {
  const { page, limit } = val;
  formModel.value.limit = Number(limit);
  formModel.value.page = Number(page);
  fetchData();
};
// 刷新
const search = () => {
  generateFormModel();
  fetchData();
};
// 重置
const reset = () => {
  formModel.value = generateFormModel();
};
const createRef = ref<any>(null);
const handleCreate = (val: any) => {
  isCreate.value = !val.id;
  createRef.value.handleClick(val);
};
const submitFrom = async (obj: any, id: any) => {
  if (isCreate.value) {
    try {
      await createUser(obj);
      Message.success('新增成功');
      fetchData();
    } finally {
      createRef.value.visible = false;
    }
  } else {
    try {
      await updateUser(obj, id);
      Message.success('编辑成功');
      fetchData();
    } finally {
      createRef.value.visible = false;
    }
  }
};
// 删除
const delRef = ref<any>(null);
const handleDel = (val: any) => {
  delRef.value.handleDelClick(val);
};
const submitDel = async (id: any) => {
  try {
    await deleteUser(id);
    Message.success('删除成功');
    fetchData();
  } finally {
    delRef.value.visible = false;
  }
};
</script>

<script lang="ts">
export default {
  name: 'SearchTable',
};
</script>

<style scoped lang="less">
.container_box {
  padding: 0 20px 20px 20px;
  
}
// .flex{
//   flex: 200 0 0;
// }
.tree_style {
  border-right: 1px solid #ccc;
  padding-top: 16px;
  margin-right: 16px;
  // flex-basis: 220px;
  width: 200px;
  height: calc(100vh - 224px);
}
.action_icon {
  margin-left: 12px;
  cursor: pointer;
}
:deep(.arco-card-size-medium .arco-card-body) {
  padding: 0 16px;
}
:deep(.arco-btn-text, .arco-btn-text[type='button']) {
  padding: 0;
  margin-right: 8px;
  &:last-child {
    margin-right: 0;
  }
}
:deep(.arco-table) {
  overflow-y: auto;
  height: calc(100vh - 338px);
}
</style>
